package registry

import (
	"crypto/tls"
	"encoding/json"
	"fmt"
	"kubeInstall/pkg/client/http"
	rawhttp "net/http"
)

var registryClient *http.Client

func init() {
	c := initClient()
	if registryClient == nil {
		registryClient = c
	}
}

func initClient() *http.Client {
	conf := http.NewConfig()
	var tlsConfig = &tls.Config{
		InsecureSkipVerify: true,
	}
	conf.HttpTransport = &rawhttp.Transport{
		TLSClientConfig: tlsConfig,
	}

	c := http.NewClient(conf)
	c.HandleError = newSystemServerError
	return c
}

func newSystemServerError(httpStatus int, responseContent string) error {
	var harborError HarborError

	err := json.Unmarshal([]byte(responseContent), &harborError)
	if err != nil {
		fmt.Println(err)
		err = fmt.Errorf("error code is %d , message is %s", httpStatus, responseContent)
		return err
	}

	return harborError
}

type Errors struct {
	Code    string `json:"code"`
	Message string `json:"message"`
}

func (api Errors) Error() string {
	var result string
	if api.Message != "" {
		result = api.Message
	}
	result = fmt.Sprintf("error code is %s , message is %s", api.Code, api.Message)
	return result
}

type HarborError struct {
	Errors []Errors `json:"errors"`
}

func (h HarborError) Error() string {
	var result string
	for _, e := range h.Errors {
		if e.Message != "" {
			result = e.Message
			break
		}
	}
	if result == "" {
		result = fmt.Sprintf("error code is %s , message is %s", h.Errors[0].Code, h.Errors[0].Message)
	}
	return result

}
